#include "GObserver.h"
#include "GObservable.h"

#include <algorithm>

namespace GUtil
{

	void GObserver::AppendObservable(GObservable* Observable)
	{
		Observables.push_front(Observable);
	}

	void GObserver::RemoveObservable(GObservable* Observable)
	{
		Observables.remove(Observable);
	}

	GObserver::GObserver()
	{
		ObserverType = 0;
	}

	GObserver::~GObserver()
	{
		UnbindFromObservables();
	}

	struct GObserverUnbinder
	{
		GObserver* ToRemove;

		void operator () (GObservable* Observable)
		{
			Observable->RemoveObserver(ToRemove);
		}
	};

	void GObserver::UnbindFromObservables()
	{
		GObserverUnbinder Unbinder;
		Unbinder.ToRemove = this;

		std::for_each(Observables.begin(), Observables.end(), Unbinder);
		Observables.clear();
	}

	void GObserver::SetObserverType(GObserverType Type)
	{
		ObserverType = Type;
	}

	GObserverType GObserver::GetObserverType() const
	{
		return ObserverType;
	}

}; // namespace GUtil